import 'package:flutter/material.dart';
import 'package:safety_platform/models/task.dart';
import 'package:safety_platform/iconfont.dart';
// import 'package:safety_platform/models/task_item.dart';
import 'package:sticky_headers/sticky_headers.dart';
import 'package:safety_platform/bloc/task/task.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:image_picker/image_picker.dart';
import 'package:safety_platform/models/attachment.dart';
import 'dart:io';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter_spinkit/flutter_spinkit.dart';

class TaskDetailWidget extends StatefulWidget {
  final Task task;

  TaskDetailWidget(this.task);

  @override
  State<StatefulWidget> createState() {
    return _TaskDetailWidgetState();
  }
}

class _TaskGroup {
  _TaskGroup(this.group);
  TaskItemGroup group;
  List<_TaskItem> items = [];
}

class _TaskItem {
  TaskItem item;
  bool showRemark = false;
  TextEditingController _controller;
  _TaskItem(this.item) : _controller = TextEditingController();

  void setValue(String value) {
    _controller.text = value;
  }
}

class _TaskDetailWidgetState extends State<TaskDetailWidget> {
  TaskBloc _bloc;
  Map<int, _TaskGroup> _itemGroups = {};

  List<int> _groupKeys;
  @override
  void initState() {
    super.initState();
    _bloc = BlocProvider.of<TaskBloc>(context);
    for (TaskItem item in widget.task.items) {
      TaskItemGroup group = item.content.category;
      if (!_itemGroups.containsKey(group.id)) {
        _itemGroups[group.id] = _TaskGroup(group);
      }
      _TaskGroup _taskGroup = _itemGroups[group.id];
      _taskGroup.items.add(_TaskItem(item));
    }
    _groupKeys = _itemGroups.keys.toList();
  }

  @override
  Widget build(BuildContext context) {
    return ListView.builder(
        itemCount: _itemGroups.length,
        itemBuilder: (BuildContext context, int index) {
          _TaskGroup taskGroup = _itemGroups[_groupKeys[index]];
          return StickyHeader(
            overlapHeaders: false,
            header: Container(
                child: ListTile(
                    title: Text('检查项目: ${taskGroup.group.title}',
                        style: TextStyle(
                          fontWeight: FontWeight.bold,
                          // color: Colors.white,
                        ))),
                color: Color.fromARGB(255, 241, 241, 241)),
            content: Container(
              child: Column(
                children: _buildItems(context, taskGroup.items),
              ),
              color: Color.fromARGB(255, 235, 235, 235),
            ),
          );
        });
  }

  List<Widget> _buildItems(BuildContext context, List<_TaskItem> items) {
    int index = 0;
    List<Widget> widgets = items.map((item) {
      index++;
      return Container(
          // color: Colors.,
          child: Card(
            elevation: 0,
            color: Colors.white,
            child: Column(
              children: <Widget>[
                _buildContext(item, index),
                _buildAttachments(item.item),
                _buildRemark(item),
                _buildAction(item),
              ],
            ),
          ),
          margin: EdgeInsets.fromLTRB(8, 0, 8, 0));
    }).toList();
    return widgets;
  }

  _onCamera(_TaskItem _item) {
    TaskItem item = _item.item;
    ImagePicker.pickImage(source: ImageSource.camera).then((File file) {
      if (file != null) {
        int index =
            (item.attachments != null) ? item.attachments.length + 1 : 1;
        Attachment attachment = Attachment(
            null, null, file.path, 'pending', 'taskitem-${item.id}-$index.jpg');
        _bloc.dispatch(UploadAttachmentEvent(item, attachment));
      }
    });
  }

  _onRemark(_TaskItem item) {
    setState(() {
      item.showRemark = true;
      item.setValue(item.item.content.negativeDetail);
    });
    print('_onRemark');
  }

  List<Widget> _buildIconAction(_TaskItem _item) {
    TaskItem item = _item.item;
    Widget _iconAction(IconData data, Function cb) {
      return Expanded(
        child: GestureDetector(
          onTap: () {
            cb(_item);
          },
          child: Container(
            height: 40,
            decoration: BoxDecoration(
              border: Border(
                right: BorderSide(
                  width: 0.5,
                  color: Color.fromARGB(255, 241, 241, 241),
                ),
              ),
            ),
            child: Padding(
                padding: EdgeInsets.all(8),
                child: Center(
                    child: Icon(
                  data,
                  size: 24,
                  color: Colors.grey,
                ))),
          ),
        ),
      );
    }

    List<Widget> widgets = List();
    widgets.add(_iconAction(MyIconFont.xiangji, _onCamera));
    widgets.add(_iconAction(MyIconFont.dingdan, _onRemark));

    widgets.add(
      GestureDetector(
        onTap: () {
          TaskBloc bloc = BlocProvider.of<TaskBloc>(context);

          bloc.dispatch(CleanTaskItemStatusEvent(item));
          setState(() {
            _item.showRemark = null;
            _item.setValue(null);
          });
        },
        child: Container(
          width: 100,
          child: Padding(
            padding: EdgeInsets.fromLTRB(16, 8, 16, 8),
            child: Center(
              child: Icon(MyIconFont.lajitong, color: Colors.grey, size: 24),
            ),
          ),
        ),
      ),
    );
    return widgets;
  }

  _buildAnswers(TaskItem taskItem, List<String> answers) {
    List<Widget> widgets = List();

    for (String answer in answers) {
      widgets.add(
        Expanded(
          child: GestureDetector(
            onTap: () {
              print('选择答案：$answer');
              TaskBloc bloc = BlocProvider.of<TaskBloc>(context);

              bloc.dispatch(
                  TaskItemStatueChangedEvent(taskItem, answer: answer));
              print('事件发送完毕');
              // setState(() {
              //   taskItem.result = answer;
              // });
            },
            child: Container(
              height: 40,
              decoration: BoxDecoration(
                // color: Colors.yellow,
                border: Border(
                  right: BorderSide(
                    color: Color.fromARGB(255, 241, 241, 241),
                    width: 0.5,
                  ),
                ),
              ),
              // child: Expanded(
              child: Padding(
                padding: EdgeInsets.all(10),
                child: Center(
                  child: Text(answer),
                  // child: Icon(
                  //   MyIconFont.dingdan,
                  //   color: Colors.grey,
                  //   size: 24,
                ),
              ),
            ),
          ),
        ), // ),
      );
    }

    if (taskItem.content.canIgnore) {
      widgets.add(Expanded(
        child: Container(
          height: 40,
          decoration: BoxDecoration(
            // color: Colors.yellow,
            border: Border(
              right: BorderSide(
                color: Color.fromARGB(255, 241, 241, 241),
                width: 1,
              ),
            ),
          ),
          // child: Expanded(
          child: Padding(
            padding: EdgeInsets.all(10),
            child: Center(
              child: Text('不适用'),
              // child: Icon(
              //   MyIconFont.dingdan,
              //   color: Colors.grey,
              //   size: 24,
            ),
          ),
        ),
        flex: 1,
      ));
    }
    return widgets;
  }

  _buildAction(_TaskItem _item) {
    TaskItem item = _item.item;
    List<String> answers = item.content.answers.split(',');

    List<Widget> answersWidget = List();

    if (item.result == null) {
      answersWidget = _buildAnswers(item, answers);
    } else {
      answersWidget = _buildIconAction(_item);
    }
    // for (String answer in answers) {
    //   answersWidget.add(
    //     Expanded(
    //       child: Container(
    //         decoration: BoxDecoration(
    //           // color: Colors.yellow,
    //           border: Border(
    //             right: BorderSide(
    //               color: Color.fromARGB(255, 241, 241, 241),
    //               width: 1,
    //             ),
    //           ),
    //         ),
    //         // child: Expanded(
    //         child: Padding(
    //           padding: EdgeInsets.all(10),
    //           child: Center(
    //             //   child: Text(answer),
    //             child: Icon(
    //               MyIconFont.dingdan,
    //               color: Colors.grey,
    //               size: 24,
    //             ),
    //           ),
    //         ),
    //         // ),
    //       ),
    //     ),
    //   );
    // }
    // answersWidget.add(
    //   Container(
    //     child: Padding(
    //       padding: EdgeInsets.all(10),
    //       child: Center(
    //         child: Icon(MyIconFont.dingdan, color: Colors.grey, size: 24),
    //       ),
    //     ),
    //   ),
    // );
    return Container(
      // padding: EdgeInsets.fromLTRB(0, 8, 0, 8),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: answersWidget,
      ),
    );
  }

  Widget _buildRemark(_TaskItem _item) {
    TaskItem item = _item.item;
    print('Show Remark: ${_item.showRemark}');
    if (_item.showRemark == null || !_item.showRemark) {
      return Container();
    }
    return Container(
      margin: EdgeInsets.fromLTRB(0, 0, 0, 0),
      color: Color.fromARGB(255, 246, 247, 250),
      child: Container(
        color: Colors.white,
        margin: EdgeInsets.all(14),
        child: TextField(
          controller: _item._controller,
          maxLines: 4,
          maxLength: 200,
          textInputAction: TextInputAction.send,
          onSubmitted: (value) =>
              _bloc.dispatch(TaskItemStatueChangedEvent(item, remark: value)),
          // onChanged: (value) => _submitRemark(item, value),
          decoration: InputDecoration(
              contentPadding: EdgeInsets.all(4),
              hintText: '请输入备注',
              border: InputBorder.none,
              hintStyle: TextStyle(
                fontSize: 14,
              )),
        ),
      ),
    );
  }

  Widget _buildAttachments(TaskItem item) {
            print('attachment =>${item.attachments}');

    if (item.attachments != null && item.attachments.length > 0) {
      List<Widget> children = item.attachments.map<Widget>((attachment) {
        Widget child;
        print('updateStatus ${attachment.uploadStatus}');
        if (attachment.uploadStatus == 'done' || attachment.uploadStatus == null) {
          Widget placeHolder ;
          if (attachment.localPath != null) {
            placeHolder =Image.file(File(attachment.localPath),
                fit: BoxFit.fill, width: 80, height: 80);
          } else {
            placeHolder = Center(child:
              CircularProgressIndicator(backgroundColor: Colors.white,));
          }
          child = CachedNetworkImage(
            imageUrl: attachment.url,
            fadeInDuration: Duration(milliseconds: 0),
            fadeOutDuration: Duration(milliseconds: 0),
            placeholder: placeHolder,
            errorWidget: new Icon(Icons.error),
            fit: BoxFit.fill,
          );
        } else {
          child = Stack(
            children: <Widget>[
              Image.file(File(attachment.localPath),
                  fit: BoxFit.fill, width: 80, height: 80),
              Center(child: CircularProgressIndicator()),
            ],
          );
        }
        // if (attachment.localPath != null) {
        //   child = Stack(
        //     children: <Widget>[
        //       Image.file(File(attachment.localPath),
        //           fit: BoxFit.fill, width: 80, height: 80),
        //       CircularProgressIndicator(),
        //     ],
        //   );
        // } else {
        //   if (attachment.url != null) {
        //     child = CachedNetworkImage(
        //       imageUrl: attachment.url,
        //       placeholder: Center(
        //         child: SpinKitCircle(
        //             size: 50, color: Theme.of(context).primaryColor),
        //       ),
        //       errorWidget: new Icon(Icons.error),
        //       fit: BoxFit.fill,
        //     );
        //   }
        // }
        return Container(
            width: 80,
            height: 80,
            margin: EdgeInsets.fromLTRB(8, 4, 8, 4),
            child: child);
      }).toList();

      return Container(
        padding: EdgeInsets.all(4),
        decoration: BoxDecoration(
          color: Color.fromARGB(255, 246, 247, 250),
          border: Border(
            bottom: BorderSide(
              color: Color.fromARGB(255, 241, 241, 241),
              width: 1,
            ),
          ),
        ),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.start,
          children: children,
        ),
      );
    }
    return Container();
  }

  _buildContext(
    _TaskItem _item,
    int index,
  ) {
    TaskItem item = _item.item;
    _badget() {
      final Color rightAnswerColor = Color.fromARGB(255, 58, 116, 214);
      final Color negtiveAnswerColor = Color.fromARGB(255, 230, 140, 38);

      if (item.result != null) {
        var color = item.result == item.content.rightAnswer
            ? rightAnswerColor
            : negtiveAnswerColor;
        return Container(
          // margin: EdgeInsets.only(top: 10),
          padding: EdgeInsets.fromLTRB(6, 4, 6, 4),
          decoration: BoxDecoration(
            color: color,
          ),
          child: Text(
            item.result,
            style: TextStyle(
              color: Colors.white,
            ),
          ),
        );
      } else {
        return Container(
          width: 24,
        );
      }
    }

    return Container(
      // height: 60,
      decoration: BoxDecoration(
          // color:Colors.red,

          border: Border(
              bottom: BorderSide(
        color: Color.fromARGB(251, 241, 241, 241),
        width: 0.5,
      ))),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          Padding(
            padding: EdgeInsets.all(8),
            child: SizedBox(
              height: 40,
              // width: 40,
              child: Column(
                children: <Widget>[
                  Text(
                    (index).toString(),
                    style: TextStyle(
                      fontSize: 20,
                      fontWeight: FontWeight.w600,
                    ),
                  ),
                ],
              ),
            ),
          ),
          Expanded(
            child: Container(
              padding: EdgeInsets.all(12),
              child: Text('${item.content.content}'),
            ),
          ),
          _badget(),
        ],
      ),
    );
  }
}
